package cn.genmer.test.security.amap;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.*;

// http://www.cnblogs.com/charlexu/p/3424963.html
public class JsInServer {

    public static void main(String[]arg)throws IOException
    {
        // 得到一个ScriptEngine对象
        ScriptEngineManager maneger = new ScriptEngineManager();
        ScriptEngine engine = maneger.getEngineByName("JavaScript");

        // 读js文件
        String jsFile = "D:\\中通快运\\main.js";
        FileInputStream fileInputStream = new FileInputStream(new File(jsFile));
        Reader scriptReader = new InputStreamReader(fileInputStream, "utf-8");

        try
        {
            engine.eval(scriptReader);
            if (engine instanceof Invocable)
            {
                // 调用JS方法
                Invocable invocable = (Invocable)engine;
                String result = (String)invocable.invokeFunction("addScript", "https://webapi.amap.com/maps?v=2.0&key=2e968e807406c2aeace6cae93fc7a1ae");
                System.out.println(result);
                System.out.println(result.length());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            scriptReader.close();
        }
    }
}